package com.zlq.cn.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zlq.cn.cache.RedisCacheService;
import com.zlq.cn.cache.RedisKey;
import com.zlq.cn.entity.User;
import com.zlq.cn.service.un.UserService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class UserSchedulerTask {
    @Resource
    private UserService userService;
    @Resource
    private RedisCacheService redisCacheService;

    // 每天凌晨触发,检测vip过期
    @Scheduled(cron = "0 0 1 * * ? ")
    public void vipTimeoutTask() {
        try {
            List<User> users = userService.list(new LambdaQueryWrapper<User>().lt(User::getVipEndTime, LocalDateTime.now()));
            if (!CollectionUtils.isEmpty(users)) {
                for (User user : users) {
                    // 更新缓存中的用户vip剩余天数
                    User cacheUser = redisCacheService.get(RedisKey.createUserKey(user.getId()));
                    if (cacheUser != null) {
                        cacheUser.setSurplusDay(0);
                        cacheUser.setVipLevel(0);
                        userService.updateSurplusDay(cacheUser);
                        redisCacheService.set(RedisKey.createUserKey(user.getId()), cacheUser);
                    }
                }
            }
        } catch (Exception ignored) {

        }
    }
}
